<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="课程类型" prop="classTypeId">
          <el-select v-model="formData.classTypeId" placeholder="请选择" style="width: 150px">
            <el-option
              v-for="item in classTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="教练" prop="trainerId">
          <el-select v-model="formData.trainerId" placeholder="请选择" style="width: 150px">
            <el-option
              v-for="item in trainerOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="queryParams.startTime"
            type="daterange"
            range-separator="~"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon><Search /></template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon><Refresh /></template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button
          v-hasPerm="['gym:classSchedules:add']"
          type="success"
          @click="handleOpenDialog()"
        >
          <template #icon><Plus /></template>
          新增
        </el-button>
        <el-button
          v-hasPerm="['gym:classSchedules:delete']"
          type="danger"
          :disabled="removeIds.length === 0"
          @click="handleDelete()"
        >
          <template #icon><Delete /></template>
          删除
        </el-button>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="pageData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          key="classTypeId"
          label="课程类型"
          prop="classTypeId"
          min-width="150"
          align="center"
          :formatter="(row) => formatClassType(row.classTypeId)"
        />
        <el-table-column
          key="trainerId"
          label="教练"
          prop="trainerId"
          min-width="150"
          align="center"
          :formatter="(row) => formatTrainer(row.trainerId)"
        />

        <el-table-column
          key="location"
          label="上课地点"
          prop="location"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="maxCapacity"
          label="最大容量"
          prop="maxCapacity"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="startTime"
          label="开始时间"
          prop="startTime"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="endTime"
          label="结束时间"
          prop="endTime"
          min-width="150"
          align="center"
        />
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
              v-hasPerm="['gym:classSchedules:edit']"
              type="primary"
              size="small"
              link
              @click="handleOpenDialog(scope.row.id)"
            >
              <template #icon><Edit /></template>
              编辑
            </el-button>
            <el-button
              v-hasPerm="['gym:classSchedules:delete']"
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            >
              <template #icon><Delete /></template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery()"
      />
    </el-card>

    <!-- 课程安排表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="课程类型" prop="classTypeId">
          <el-select v-model="formData.classTypeId" placeholder="请选择">
            <el-option
              v-for="item in classTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="教练" prop="trainerId">
          <el-select v-model="formData.trainerId" placeholder="请选择">
            <el-option
              v-for="item in trainerOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="formData.startTime"
            type="datetime"
            placeholder="开始时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="formData.endTime"
            type="datetime"
            placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <el-form-item label="最大容量" prop="maxCapacity">
          <el-input v-model="formData.maxCapacity" placeholder="最大容量" />
        </el-form-item>

        <el-form-item label="上课地点" prop="location">
          <el-input v-model="formData.location" placeholder="上课地点" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "ClassSchedules",
  inheritAttrs: false,
});

import ClassSchedulesAPI, {
  ClassSchedulesPageVO,
  ClassSchedulesForm,
  ClassSchedulesPageQuery,
} from "@/api/gym/class-schedules";

import ClassTypesAPI from "@/api/gym/class-types";
import UserAPI from "@/api/system/user.api";
const queryFormRef = ref();
const dataFormRef = ref();

const loading = ref(false);
const removeIds = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<ClassSchedulesPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 课程安排表格数据
const pageData = ref<ClassSchedulesPageVO[]>([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 课程安排表单数据
const formData = reactive<ClassSchedulesForm>({});

// 课程安排表单校验规则
const rules = reactive({
  classTypeId: [{ required: true, message: "请输入课程类型ID", trigger: "blur" }],
  trainerId: [{ required: true, message: "请输入教练ID", trigger: "blur" }],
  startTime: [{ required: true, message: "请输入开始时间", trigger: "blur" }],
  endTime: [{ required: true, message: "请输入结束时间", trigger: "blur" }],
  maxCapacity: [{ required: true, message: "请输入最大容量", trigger: "blur" }],
  location: [{ required: true, message: "请输入上课地点", trigger: "blur" }],
});

// 课程类型下拉数据源
const classTypeOptions = ref<OptionType[]>();

const formatClassType = (id: string | number) => {
  const option = classTypeOptions.value?.find((item) => item.value == id);
  return String(option?.label || id); // 若未匹配到则显示原始id
};
// 教练下拉数据源
const trainerOptions = ref<OptionType[]>();
const formatTrainer = (id: string | number) => {
  const option = trainerOptions.value?.find((item) => item.value == id);
  return String(option?.label || id); // 若未匹配到则显示原始id
};
/** 打开课程安排弹窗 */
async function handleOpenDialog(id?: number) {
  dialog.visible = true;

  if (id) {
    dialog.title = "修改课程安排";
    ClassSchedulesAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增课程安排";
  }
}

/** 查询课程安排 */
function handleQuery() {
  loading.value = true;
  ClassSchedulesAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置课程安排查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 提交课程安排表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        ClassSchedulesAPI.update(id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        ClassSchedulesAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭课程安排弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = undefined;
}

/** 删除课程安排 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      ClassSchedulesAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

onMounted(() => {
  handleQuery();
});
// 页面挂载后执行
onMounted(async () => {
  try {
    classTypeOptions.value = await ClassTypesAPI.getOptions();
  } catch (error) {
    console.error("获取课程类型失败", error);
    // 可添加错误提示（如使用 Element Plus 的 Message）
  }
  try {
    trainerOptions.value = await UserAPI.getRoleOptions(14);
  } catch (error) {
    console.error("获取课程类型失败", error);
    // 可添加错误提示（如使用 Element Plus 的 Message）
  }

  handleQuery();
});
</script>
